/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.emergencyStatement.web;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.opsli.api.web.business.emergencyStatement.EmergencyStatementRestApi;
import org.opsli.api.wrapper.business.emergencyStatement.EmergencyStatementModel;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.emergencyStatement.entity.EmergencyStatement;
import org.opsli.modulars.business.emergencyStatement.service.IEmergencyStatementService;
import org.opsli.modulars.business.patrolRouteRecord.entity.DailyInspectionReport;
import org.opsli.modulars.business.patrolRouteRecord.web.DailyInspectionReportController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import reactor.core.publisher.EmitterProcessor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 隐患报表 Controller
 *
 * @author Ljc
 * @date 2022-03-28 14:41:21
 */
@Api(tags = EmergencyStatementRestApi.TITLE)
@Slf4j
@ApiRestController("/emergencyStatement")
public class EmergencyStatementRestController extends BaseRestController<EmergencyStatement, EmergencyStatementModel, IEmergencyStatementService> {


    @Autowired
    IEmergencyStatementService statementService;

    private List listAll;//存储列表数据 以便于导出
    /**
    * 隐患报表 查询分页
    * @param pageNo 当前页
    * @param pageSize 每页条数
    * @param request request
    * @return ResultVo
    */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @GetMapping("/findPage")

    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request,String emergencyTitle) {
        UserModel user= UserUtil.getSysUser();

        EmergencyStatement emergencyStatement =new EmergencyStatement();
        emergencyStatement.setDevid(user.getCompanyId());
        emergencyStatement.setEmergencyTitle(emergencyTitle);
        List<EmergencyStatement> list=statementService.findLists(emergencyStatement);
        listAll=list;
        //将合并的list进行分页
        Page page = new Page(pageNo, pageSize);
        int totalLength = list.size(); //总的数据条数
        int totalPage = totalLength % pageSize == 0 ? totalLength / pageSize : totalLength / pageSize + 1; //总的页数
        List pageData = null;
        if (pageNo < totalPage) {
            int startIndex = (pageNo - 1) * pageSize;
            int endIndex = startIndex + pageSize - 1;
            pageData = list.subList(startIndex, endIndex + 1);
        } else {
            int startIndex = (pageNo - 1) * pageSize;
            pageData = list.subList(startIndex, totalLength);//最后一页
        }
        page.setList(pageData);
        page.setTotal(list.size());
        return ResultVo.success(page.getPageData());
    }

    //导出巡检月报表Excel
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    public void getExportExcel(HttpServletRequest request, HttpServletResponse response) {

        List l = listAll;
        String titleName = "隐患报表";
        DailyInspectionReportController drc = new DailyInspectionReportController();
        //输出文件流
        OutputStream output = null;
        try {
            output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition",
                    "attchement;filename=" + new String(("隐患报表" + ZkUtils.getDateStr().substring(0, 10) + ".xls").getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/msexcel");
        } catch (IOException e) {
            e.printStackTrace();
        }
        HSSFWorkbook book = null;
        try {
            book = new HSSFWorkbook(this.getExcelFile(l, titleName));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            book.write(output);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            output.flush();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            output.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

    }

    //导出Excel样式
    private HSSFWorkbook workbook;
    private HSSFSheet sheet;

    public InputStream getExcelFile(List l, String titleName) throws IOException {
        //获取当前系统时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String sheetName = df.format(new Date());
        //创建sheet
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet(sheetName);
        //字体样式
        HSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);// 字体大小
        //字体加粗样式
        HSSFFont font0 = workbook.createFont();
        font0.setFontName("宋体");
        font0.setFontHeightInPoints((short) 20);
        font0.setBold(true);
        //通用字体样式
        HSSFCellStyle cs0 = workbook.createCellStyle();//创建第一行样式
//        cs0.setAlignment(HorizontalAlignment.CENTER);// 左右居中2 居右3 默认居左
        cs0.setFont(font);
        cs0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中1
        cs0.setBorderBottom(BorderStyle.THIN);
        cs0.setBorderLeft(BorderStyle.THIN);
        cs0.setBorderRight(BorderStyle.THIN);
        cs0.setBorderTop(BorderStyle.THIN);

        //字体加粗样式
        HSSFCellStyle css0 = workbook.createCellStyle();//创建第一行样式
//        css0.setAlignment(HorizontalAlignment.CENTER);
        css0.setFont(font0);

        HSSFRow h0 = sheet.createRow(0);//创建一行
        HSSFCell c0 = h0.createCell(0);//在第一行创建一个cell
        c0.setCellValue(titleName);//设置头部标题
        c0.setCellStyle(css0);
        CellRangeAddress cra0 = new CellRangeAddress(0, 0, 0, 11);//合并行
        sheet.addMergedRegion(cra0);
        setBorderStyle(1, cra0, sheet, workbook);

        HSSFRow h1 = sheet.createRow(1);//获取第二行

        HSSFCell c1 = h1.createCell(0);//巡检员
        c1.setCellValue("隐患标题");
        c1.setCellStyle(cs0);
        HSSFCell c2 = h1.createCell(1);//巡检员
        c2.setCellValue("上报人");
        c2.setCellStyle(cs0);
        HSSFCell c3 = h1.createCell(2);//巡检员
        c3.setCellValue("上报时间");
        c3.setCellStyle(cs0);
        HSSFCell c4 = h1.createCell(3);//巡检员
        c4.setCellValue("位置描述");
        c4.setCellStyle(cs0);
        HSSFCell c5 = h1.createCell(4);//巡检员
        c5.setCellValue("上报描述");
        c5.setCellStyle(cs0);
        HSSFCell c6 = h1.createCell(5);//巡检员
        c6.setCellValue("任务下发人");
        c6.setCellStyle(cs0);
        HSSFCell c7 = h1.createCell(6);//巡检员
        c7.setCellValue("任务下发时间");
        c7.setCellStyle(cs0);
        HSSFCell c8 = h1.createCell(7);//巡检员
        c8.setCellValue("处理意见");
        c8.setCellStyle(cs0);
        HSSFCell c9 = h1.createCell(8);//巡检员
        c9.setCellValue("维修员名称");
        c9.setCellStyle(cs0);
        HSSFCell c10 = h1.createCell(9);//巡检员
        c10.setCellValue("完成时间");
        c10.setCellStyle(cs0);
        HSSFCell c11 = h1.createCell(10);//巡检员
        c11.setCellValue("隐患原因");
        c11.setCellStyle(cs0);
        HSSFCell c12 = h1.createCell(11);//巡检员
        c12.setCellValue("隐患结果");
        c12.setCellStyle(cs0);

        for (int s = 0; s <= 11; s++) {
            sheet.setColumnWidth(s, 5000);
        }
        for (int h = 0; h < l.size(); h++) {
            EmergencyStatement di = (EmergencyStatement) l.get(h);
            int n = 2 + h;
            HSSFRow h4 = sheet.createRow(n);
            HSSFCell c01 = h4.createCell(0);
            c01.setCellValue(di.getEmergencyTitle());/** 隐患标题 */
            c01.setCellStyle(cs0);
            HSSFCell c02 = h4.createCell(1);
            c02.setCellValue(di.getUserName());/** 上报人 */
            c02.setCellStyle(cs0);
            HSSFCell c03 = h4.createCell(2);
            c03.setCellValue(di.getReportTime());/** 上报时间 */
            c03.setCellStyle(cs0);
            HSSFCell c04 = h4.createCell(3);
            c04.setCellValue(di.getLocation());/** 位置描述 */
            c04.setCellStyle(cs0);
            HSSFCell c05 = h4.createCell(4);
            c05.setCellValue(di.getDescription());/** 上报描述 */
            c05.setCellStyle(cs0);
            HSSFCell c06 = h4.createCell(5);
            c06.setCellValue(di.getRealName());/** 任务下发人 */
            c06.setCellStyle(cs0);
            HSSFCell c07 = h4.createCell(6);
            c07.setCellValue(di.getBeginTime());/** 隐患标题 */
            c07.setCellStyle(cs0);
            HSSFCell c08 = h4.createCell(7);
            c08.setCellValue(di.getFeedback());/** 任务下发时间 */
            c08.setCellStyle(cs0);
            HSSFCell c09 = h4.createCell(8);
            c09.setCellValue(di.getWxName());/** 维修员名称 */
            c09.setCellStyle(cs0);
            HSSFCell c010 = h4.createCell(9);
            c010.setCellValue(di.getEndTime());/** 完成时间 */
            c010.setCellStyle(cs0);
            HSSFCell c011 = h4.createCell(10);
            c011.setCellValue(di.getDefectCause());/** 隐患原因 */
            c011.setCellStyle(cs0);
            HSSFCell c012 = h4.createCell(11);
            c012.setCellValue(di.getDefectResult());/** 隐患结果 */
            c012.setCellStyle(cs0);

        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        byte[] ba = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(ba);
        return bais;
    }

    //加边框
    private static void setBorderStyle(int border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook wb) {
        HSSFCellStyle cs = wb.createCellStyle(); // 样式对象
        HSSFFont font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);
        cs.setFont(font);
        cs.setAlignment(HorizontalAlignment.CENTER);
        cs.setVerticalAlignment(VerticalAlignment.CENTER);
        cs.setBorderBottom(BorderStyle.valueOf((short) border));
        cs.setBorderTop(BorderStyle.valueOf((short) border));
        cs.setBorderLeft(BorderStyle.valueOf((short) border));
        cs.setBorderRight(BorderStyle.valueOf((short) border));
        setRegionStyle(cs, region, sheet);
    }

    private static void setRegionStyle(HSSFCellStyle cs, CellRangeAddress region, HSSFSheet sheet) {
        for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
            HSSFRow row = sheet.getRow(i);
            if (row == null) row = sheet.createRow(i);
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                HSSFCell cell = row.getCell(j);
                if (cell == null) {
                    cell = row.createCell(j);
                    cell.setCellValue("");
                }
                cell.setCellStyle(cs);
            }
        }
    }

}